package main

import (
	"demo02/文件列表服务/filelist"
	"log"
	"net/http"
	"os"
)

// 统一错误处理
type appHandler func(writer http.ResponseWriter, request *http.Request) error

func errWrapper(handler appHandler) func(http.ResponseWriter, *http.Request) {
	return func(writer http.ResponseWriter, request *http.Request) {
		err := handler(writer, request)
		if err != nil {
			log.Printf("Error handler request:%s \n", err.Error())
			code := http.StatusOK
			switch {
			case os.IsNotExist(err):
				// 文件没找到
				code = http.StatusNotFound
			case os.IsPermission(err):
				code = http.StatusForbidden
			default:
				// 服务器错误
				code = http.StatusInternalServerError
			}

			http.Error(writer, http.StatusText(code), code)
		}
	}
}

// 显示文件的server
func main() {
	http.HandleFunc("/list/", errWrapper(filelist.FileListHandler))

	err := http.ListenAndServe(":8888", nil)
	if err != nil {
		panic(err)
	}
}
